package com.tlgen.tomcat.utils;

import com.tlgen.tomcat.model.HttpRequestResponse;
import com.tlgen.tomcat.model.Request;
import com.tlgen.tomcat.model.Response;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class SocketParserUtils {

    /**
     * 将 socket 封装 request 对象
     *
     * @param requestLine
     * @return
     */
    public static HttpRequestResponse createRequestResponse(String requestLine) throws IOException {
        HttpRequestResponse httpRequestResponse = new HttpRequestResponse();
        Request request = buildRequest(requestLine);
        Response response = buildResponse(request);
        // 添加自定义拦截器
        ReflectionUtils.doRequestFilter(request);
        httpRequestResponse.setRequest(request);
        httpRequestResponse.setResponse(response);
        return httpRequestResponse;
    }

    /**
     * 将 socket 封装 response 对象
     *
     * @param requestLine
     * @return
     */
    public static Request buildRequest(String requestLine) {
        String requestStr = "";
        Request request = new Request();
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Content-Length", String.valueOf(requestStr.getBytes().length));
        request.setHeaders(headers);
        request.setMessage("");
        request.setMethod(StringRequestUtils.getRequestType(requestLine));
        request.setUri(StringRequestUtils.getRequestPath(requestLine));
        request.setVersion(StringRequestUtils.getRequestVersion(requestLine));
        return request;
    }

    /**
     * 将 socket 封装 response 对象
     *
     * @param request
     * @return
     */
    public static Response buildResponse(Request request) {
        String response = "";
        Response httpResponse = new Response();
        httpResponse.setCode(200);
        httpResponse.setStatus("ok");
        httpResponse.setVersion(request.getVersion());
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Content-Length", String.valueOf(response.getBytes().length));
        httpResponse.setHeaders(headers);
        httpResponse.setMessage(response);
        httpResponse.setData("");
        return httpResponse;
    }

}
